package com.shengtsource.minicat.model;

import com.shengtsource.minicat.util.HttpProtocolUtils;
import com.shengtsource.minicat.util.StaticResourceUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * 响应对象
 * @author shengtsource
 */
public class Response {

    private OutputStream outputStream;

    public Response(OutputStream outputStream) {
        this.outputStream = outputStream;
    }

    public OutputStream getOutputStream() {
        return outputStream;
    }

    public void setOutputStream(OutputStream outputStream) {
        this.outputStream = outputStream;
    }

    /**
     * 输出静态资源
     * @param path
     */
    public void outputHtml(String path) throws IOException {
        //获取静态资源的真实路径
        String realPath = StaticResourceUtils.getRealPath(path);
        // 构建文件对象
        File file = new File(realPath);
        if(file.exists() && !file.isDirectory()) {
            StaticResourceUtils.outputStaticResource(new FileInputStream(file),this.outputStream);
        }else {
            //找不到对应的资源文件
            this.outputStream.write(HttpProtocolUtils.getResponseHeader404().getBytes());
        }
    };
}
